#include "ThreadPool.h"
int exitpipe[2];
void sigFunc(int signum){
    printf("父进程即将关闭\n");
    write(exitpipe[1],"1",1);
}
int main(int argc,char* argv[]){
    //这一步是检查输入参数
    if(argc<4){
        error(1,0,"参数不足\n");
    }
    
    int WorkerNum=atoi(argv[3]);
    pipe(exitpipe);
    //这是主进程也就是父进程
    if(fork()!=0){
        close(exitpipe[0]);
        signal(SIGUSR1,sigFunc);
        wait(NULL);
        exit(0);
    }
    //**************************
    //子进程
    close(exitpipe[1]);
    //线程初始化
    threadPool_t threadPool;
    threadPool.workerNum=WorkerNum;
    threadPool.tidArry=(pthread_t*)calloc(WorkerNum,sizeof(pthread_t));
    bzero(&threadPool.taskQueue,sizeof(taskQueue_t));
    pthread_mutex_init(&threadPool.mutex,NULL);
    pthread_cond_init(&threadPool.cond,NULL);
    threadPool.exitflag=0;
    //创建网络socket
    int sockfd;
    tcpInit(argv[1],argv[2],&sockfd);
    //创建线程池
    makeWorker(&threadPool);
    //开始创建epoll监听
    int epfd=epoll_create(1);
    epollAdd(epfd,sockfd);
    epollAdd(epfd,exitpipe[0]);
    struct epoll_event readySet[1024];
    while(1){
       int readyNum= epoll_wait(epfd,readySet,1024,-1);
       for(int i=0;i<readyNum;i++){
           if(readySet[i].data.fd==sockfd){
                printf("一个子进程发来链接申请\n");
                int netfd=accept(sockfd,NULL,NULL);
                pthread_mutex_lock(&threadPool.mutex);
                enqueue(&threadPool.taskQueue,netfd);
                printf("任务队列加1\n");
                pthread_cond_signal(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
           }
           else if(readySet[i].data.fd==exitpipe[0]){
                printf("线程池即将关闭\n");
                pthread_mutex_lock(&threadPool.mutex);
                threadPool.exitflag=1;
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);


                //回收资源
                for(int i=0;i<threadPool.workerNum;i++){
                    pthread_join(threadPool.tidArry[i],NULL);
                }
                printf("所有服务线程已关闭\n");
                pthread_exit(NULL);

           }
       }
    }
}
